package com.helloworld.service;

import com.helloworld.mapper.RoleMapper;
import com.helloworld.pojo.Role;
import com.helloworld.vo.Role.RoleAddReq;
import com.helloworld.vo.Role.RoleInfo;
import com.helloworld.vo.Role.RoleUpdateReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleService {
    @Autowired
    private RoleMapper roleMapper;

    public Integer  addRole(RoleAddReq req){
        Role role = Role.builder()
                .name(req.getName())
                .build();
        roleMapper.addRole(role);
        return role.getId();
    }

    public void updateRole(RoleUpdateReq req) {
        Role role = Role.builder()
                .id(req.getId())
                .name(req.getName())
                .build();
        roleMapper.updateRole(role);
    }

    public void deleteRole(Integer id) {
        roleMapper.deleteRole(id);
    }

    public RoleInfo queryRoleById(Integer id){
        Role role = roleMapper.queryRoleById(id);
        if(null == role){
            // throw new RuntimeException("role cannot be found by id=" + id);
            return null;
        }
        return RoleInfo.builder()
                .id(role.getId())
                .name(role.getName())
                .build();
    }

    public List<RoleInfo> queryRoleList(String nameLike) {
        List<Role> roles = roleMapper.queryRoleList(nameLike);
        if(CollectionUtils.isEmpty(roles)){
            return new ArrayList<>();
        }
        return roles.stream().map(role -> {
            return RoleInfo.builder()
                    .id(role.getId())
                    .name(role.getName())
                    .build();
        }).collect(Collectors.toList());
    }
}
